package com.jyh.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jyh.config.BaseAction;
import com.jyh.config.quantity.ConstantConfig;
import com.jyh.config.quantity.Result;
import com.jyh.config.redis.JedisClient;

import com.jyh.db.entity.JyhManager;
import com.jyh.db.entity.JyhManagerExample;
import com.jyh.db.entity.JyhRightRole;
import com.jyh.db.entity.JyhRightRoleExample;

import com.jyh.db.mapper.JyhManagerMapper;
import com.jyh.db.mapper.JyhRightRoleMapper;
import com.jyh.util.NoteUtils;
import com.jyh.util.Utils;

@Service
public class LoginService extends BaseAction {
	@Autowired
	private JyhManagerMapper managerMapper;
	@Autowired
	private JedisClient jedisClientPool;
	@Autowired
	private JyhRightRoleMapper rightRoleMapper;
	

	/**
	 * 发送短信验证码
	 * 
	 * @param tel
	 *            手机号
	 * @param pwd
	 *            密码
	 * @return
	 */
	public Result getValCode(String tel, String pwd) {
		Result result = null;
		// 得到用户
		pwd = Utils.string2MD5(pwd);
		JyhManagerExample managerExample = new JyhManagerExample();
		managerExample.createCriteria().andMobileEqualTo(tel).andPwdEqualTo(pwd).andIsLoginEqualTo(1);
		List<JyhManager> list = managerMapper.selectByExample(managerExample);
		if (list == null || list.size() == 0) {
			result = new Result("9999", "用户名或密码错误，请重新输入!");
			return result;
		}
		// 生成六位的随机数 得到手机号码 发送验证码
		String userTel = list.get(0).getMobile();
		Integer random = (int) ((Math.random() * 9 + 1) * 100000);
		// Integer random = 189363;
		logger.info("短信验证码为：" + random);
		Map<String, Object> getSMSNoteMap = new HashMap<String, Object>();
		getSMSNoteMap.put("code", random);
		// 替换短信文字关键字获取发送短信
		String smsStr = NoteUtils.getNoteSMSTextReplace(ConstantConfig.NOTESMSTEXT, getSMSNoteMap);
		// 发送短信
		if ("2".equals(ConstantConfig.NOTESMSISSEND)) {
			return new Result("0000", "短信发送成功");
		}
		String sendSMS = NoteUtils.getNoteSend(userTel, smsStr);
		com.alibaba.fastjson.JSONObject reqoobj = com.jyh.util.StringUtils.getobj(sendSMS);
		String errorCode = reqoobj.getString("errorCode");
		if ("0000".equals(errorCode)) {
			String key = "NOTEMOBILE_" + userTel;
			jedisClientPool.set(key, random + "");
			jedisClientPool.expire(key, 60 * 60);
			result = new Result("0000", "短信发送成功");
		} else {
			result = new Result("9999", "短信发送失败");
		}
		return result;
	}

	/**
	 * 验证登录
	 * 
	 * @param tel
	 *            手机号
	 * @param pwd
	 *            密码
	 * @param note
	 *            验证码
	 * @return
	 */
	public Result getVerifyLogin(String tel, String pwd, String note, HttpServletRequest request, HttpSession session) {
		Result result = null;
		pwd = Utils.string2MD5(pwd);
		JyhManagerExample managerExample = new JyhManagerExample();
		managerExample.createCriteria().andMobileEqualTo(tel).andPwdEqualTo(pwd).andIsLoginEqualTo(1);
		List<JyhManager> list = managerMapper.selectByExample(managerExample);
		if (list == null || list.size() == 0) {
			result = new Result("9999", "用户名或密码错误，请重新输入!");
			return result;
		}
		// 生成六位的随机数 得到手机号码 发送验证码
		String userTel = list.get(0).getMobile();
		// 如果为不发送验证码环境，将直接通过

		if ("2".equals(ConstantConfig.NOTESMSISSEND) && "111111".equals(note)) {
			Map<String, List<String>> mapReturn = getTransition(list.get(0).getRoleId(),request, session);
			logger.info("---登录后获取用户权限---" + mapReturn);
			session.setAttribute("manageroleId", list.get(0).getRoleId().toString());
			session.setAttribute("username", tel);
			session.setAttribute("managerName", list.get(0).getManger().toString());
			session.setAttribute("userId", list.get(0).getId());
			
			System.out.println("获取的用户ID："+session.getAttribute("userId"));
			return new Result("0000", "验证正常");
		}
		String key = "NOTEMOBILE_" + userTel;
		String getOldKey = jedisClientPool.get(key);
		if (getOldKey == null) {
			return new Result("9999", "用户所输入手机号异常");
		}
		if (!getOldKey.equals(note)) {
			return new Result("9999", "用户所输入验证码异常");
		}
		session.setAttribute("username", tel);
		session.setAttribute("userId", list.get(0).getId());
		if (!Utils.isNull(list.get(0).getRoleId())) {
			Map<String, List<String>> mapReturn = getTransition(list.get(0).getRoleId(),request, session);
			logger.info("---登录后获取用户权限---" + mapReturn);
		}
		jedisClientPool.del(key);
		return new Result("0000", "验证正常");
	}

	/**
	 * 私有方法，登陆时调用一次 登录成功加载方法，数据插入session 获取数据以MAP返回
	 * 
	 * @param name
	 *            父ID
	 * @return
	 */
	@SuppressWarnings({ "deprecation" })
	public Map<String, List<String>> getTransition(String id ,HttpServletRequest request, HttpSession session) {
		logger.info("rID:" + id);
		Map<String, List<String>> mapReturn = new HashMap<String, List<String>>();
		JyhRightRoleExample rightRoleExample = new JyhRightRoleExample();
		rightRoleExample.createCriteria().andIdEqualTo(Integer.parseInt(id));
		List<JyhRightRole> list = rightRoleMapper.selectByExample(rightRoleExample);
		if (list == null || list.size() <= 0) {
			return mapReturn;
		}
		List<String> headList = getStrToList(list.get(0).getHeadParameters());
		List<String> leftList = getStrToList(list.get(0).getLeftParameters());
		List<String> centerList = getStrToList(list.get(0).getCenterParameters());
		mapReturn.put("head", headList);
		mapReturn.put("left", leftList);
		mapReturn.put("center", centerList);
		session.setAttribute("jurisdiction", mapReturn);
		session.setAttribute("rname", list.get(0).getrRole());
		session.setAttribute("projectName", request.getContextPath());
		return mapReturn;

	}

	/**
	 * 按钮级权限加载如缓存
	 * 
	 * @param session
	 */


	/**
	 * String类型转List
	 * 
	 * @param str
	 * @return
	 */
	private static List<String> getStrToList(String str) {
		List<String> list = new ArrayList<String>();
		String[] rol = str.split(",");
		for (int i = 0; i < rol.length; i++) {
			list.add(rol[i]);
		}
		return list;
	}
}
